let {
	list
} = require('./mock')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const userList = [{
	user: 'admin',
	pwd: 'pwd',
	nickname: '管理员',
	role: ['admin'],
	signation: '我是一名管理员, 想删除谁就删除谁！！'
}, {
	user: '张三',
	pwd: '123',
	nickname: '普通',
	role: ['user'],
	signation: '很遗憾， 我只要查询权限'
}]
const key = '1werw32'
module.exports = app => {
	app.use(bodyParser.json())
	// 列表请求
	app.get('/api/list', (req, res) => {
		res.send({
			code: 200,
			data: list
		})
	})
	// 列表删除
	app.post('/api/delete', (req, res) => {
		const {
			key
		} = req.body;

		list = list.filter(v => v.key !== key);

		res.send({
			code: 200,
			message: '删除成功'
		})
	})

	// 列表修改
	app.post('/api/edit', (req, res) => {
		const {
			item
		} = req.body;
		const currItem = list.find(v => v.key === item.key);
		Object.assign(currItem, item)
		res.send({
			code: 200,
			message: '修改成功！！'
		})
	})

	// 登录
	app.post('/api/login', (req, res) => {
		const {
			user,
			pwd
		} = req.body;
		const item = userList.find(v => v.user === user && v.pwd === pwd)
		if (item) {
			res.send({
				code: 200,
				message: '登录成功',
				data: {
					token: JWT.sign({
						user: item.user,
						nickname: item.nickname,
						role: item.role,
						signation: item.signation
					}, key),
					user: item.user,
					nickname: item.nickname,
					role: item.role,
					signation: item.signation
				}
			})
		} else {
			res.send({
				code: 401,
				message: '账户密码错误， 请重新登录'
			})
		}
	})

	// 获取用户信息
	app.get('/api/user/info', (req, res) => {
		const { token } = req.query
		try {
			const data = JWT.verify(token, key)
			res.send({
				code: 200,
				message: '获取用户信息成功',
				data: {
					...data
				}
			})
		} catch(e) {
			res.send({
				code: 403,
				message: 'token 存在， 但是不正确'
			})
		}
	})
}